package tools

import (
	"database/sql"
	"fmt"
	"log"
	"os"

	_ "github.com/go-sql-driver/mysql"
)

var (
	sql_host    string  = "192.168.100.206"
	sql_port    uint    = 3306
	sql_usrname string  = "gavin"
	sql_passwd  string  = "123456"
	sql_dbname  string  = "MG_BSDB_V6"
	sql_table   string  = "D_BSInfo"
	db          *sql.DB = &sql.DB{}
	errorcount 	    uint64
	okcount		uint64
	err         error

	sqlstr string = "SELECT RecID,Lon,Lat from " + sql_dbname + "." + sql_table
)

func init() {
	//	dsn := (&mysql.Config{
	//		User:      sql_usrname,
	//		Passwd:    sql_passwd,
	//		Net:       "tcp",
	//		Addr:      fmt.Sprintf("%s:%d", sql_host, sql_port),
	//		Collation: "utf8_general_ci",
	//		DBName:    sql_dbname,
	//	}).FormatDSN()
	//	fmt.Println("dns:", dns)
	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s%s", sql_usrname, sql_passwd, sql_host, sql_port, sql_dbname, "?charset=utf8&loc=Asia%2FShanghai")
	fmt.Println("dns:", dsn)
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		fmt.Println("err in db.Open:", err.Error())
		os.Exit(-1)
	}
	err = db.Ping()
	if err != nil {
		fmt.Println("err in db.Ping:", err.Error())
		os.Exit(-1)
	}
}

func GpsTransFromDB() {
	rows, _ := db.Query(sqlstr)
	defer rows.Close()
	for rows.Next() {
		var (
			lon, lat       float64
			newlon, newlat float64
			recID 		uint64
			conver         LocationConverter
		)
		if err := rows.Scan(&recID,&lon, &lat); err != nil {
			log.Fatal(err)
			return
		}

		newlon, newlat = conver.DecryptGCJ02(lon, lat)
		okcount = okcount + 1
		fmt.Println("count",okcount,"before [ lat:", lat, "lon:", lon, " ],after [ lat: ", newlat, "lon:", newlon, "]")
		_,err := db.Exec("UPDATE MG_BSDB_V6.D_BSInfo  set Lon=?,Lat=? where RecID =  ?", newlon, newlat, recID)
		if err != nil {
			errorcount = errorcount + 1
			fmt.Println("update fail ,count:",errorcount,"reason:",err.Error())
		}

	}
}
